package com.ywy.bootadmin.config;

import com.ywy.bootadmin.task.TaskFactory;
import org.quartz.ee.servlet.QuartzInitializerListener;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;

/**
 * Quartz定时任务配置
 *
 * @author ywy
 * @date 2021/11/3 16:37
 */
@Configuration
public class QuartzConfig {
    /**
     * 配置任务调度器
     * @param taskFactory
     * @param dataSource
     * @return
     */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(TaskFactory taskFactory, DataSource dataSource) {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        try {
            // 将spring管理job自定义工厂交由调度器维护
            schedulerFactoryBean.setJobFactory(taskFactory);
            // 设置覆盖已存在的任务
            schedulerFactoryBean.setOverwriteExistingJobs(true);
            // 项目启动完成后，等待10秒后开始执行调度器初始化
            schedulerFactoryBean.setStartupDelay(10);
            // 设置调度器自动运行
            schedulerFactoryBean.setAutoStartup(true);
            // 设置数据源，使用与项目统一数据源，quartz.properties中不再指定
//            schedulerFactoryBean.setDataSource(dataSource);
            // 设置Quartz配置属性
            schedulerFactoryBean.setQuartzProperties(quartzProperties());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return schedulerFactoryBean;
    }

    /**
     * 从quartz.properties文件中读取Quartz配置属性
     * @return
     * @throws IOException
     */
    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/config/quartz.properties"));
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }

    /**
     * 初始化监听器
     *
     * @return
     */
    @Bean
    public QuartzInitializerListener executorListener() {
        return new QuartzInitializerListener();
    }
}
